/**
 * 多客服聊天系统-客户端
 * 当前版本由jQuery 书写，可以运行在PC版
 * @author 晓风<215628355@qq.com> 
 *
**/

//默认图片地址处理
function noFind(img){ 
    img.src = '/static/customer/images/face.png'  // 默认图片地址
    img.onerror = null;  // 控制不要循环展示错误
}
//socket主线业务,依赖于socket.io插件
var sockets = {
    socket : null,
    store : {},  
    user : {},
    clientHeader : 0,
    clientConnHeader : 0,
    chatConnHeader : 0, 
    autoReplay : '',
	upToken : "",
    jstoken : "",  
    client : function(param){
        var that = this;
		that.upToken = param.token;
        that.jstoken = param.jstoken;
        that.store = param.store;
        that.user = param.user;       
       
        var index =  layer.open({type: 2 , shadeClose: false});
        that.socket = new io(param.url,{
            transports: [ 'websocket']  
        });//初始化socket.io


        that.socket.on('connect', function() {
            console.log("连接成功"); 
            if(that.chatConnHeader  == 0){                
                that.socket.emit("conn",that.user)
                that.chatConnHeader = 1;
            }
            that.clientHeader = 1;
            that.error("连接到服务器");
            layer.close(index)
        });
        that.socket.on('reconnect', function() {	
            //console.log("重新连接到服务器");            
            that.clientHeader = 1;
            that.error("重新连接到服务器");
            layer.close(index)
        });
        that.socket.on("disconnect",function(){
           // console.log("与服务器断开")
            that.clientHeader = 0;
            that.error("与服务器断开");            
            index =  layer.open({type: 2,"content":"已断开", shadeClose: false});  
        })
        that.socket.on('heartbeat', function () {
            that.socket.emit("heartbeat","heartbeat");
        });
        that.socket.on("broadcastingListen",function(data){        
            for(var i=0; i< data.length; i++){
                var MESSAGE = data[i];
                console.log(MESSAGE)
                that.useMessage(MESSAGE);
            }
        })       
        that.socket.on("conn",function(code){
            if(code[0]  == "ok"){    
                that.error("注册客服服务成功");
                that.clientConnHeader = 1;
                that.init();                
            }else{                
                that.error("注册客服服务失败");
            }           
        })    
    },
    //初步分解消息
    useMessage : function(data){
        var that = this;
        var json = this.evealJson(data);   
        var metch = json.type;
		//如果客服不是我，则这条消息排除，不展示
		//在客服会话中，如果不加这个判断，会非常混乱
		if(data.store_id != that.store.store_id){
			return false;
		}
        //有时候会自己和自己聊，这个要排除下，接收到本端发的消息不要渲染
        if(data.user_id == that.user.uid  && data.form_type == 1){
			return false;
		}  
       
        switch(metch){            
            case "recall":            
				that.recallMessage(json); 
				break;            
            default:			
				this.rightAdd(json,"left")     
				break;
        }
    },
    //解析JSON
    evealJson:function(data){  
        if(typeof data != 'object'){    
            try{        
                data  = JSON.parse(data);
            }catch(err){          
                //console.log('JSON解析错误',err );
                return !1;          
            }  
        }  
        return data;    
    }, 
  
    //撤回消息
    recallMessage:function(data){
       
    },
     //将消息放在右侧窗口内
    rightAdd:function(data,leftRight){      
        var isid = $('.message-box .message ul li[msgid="'+data.msgid+'"]').size(); //排除消息重复渲染
        if(isid > 0){
            return false;
        }         
        var content = this.loadContent(data.type,data.content) ;//解析消息体
        var box = $('<li msgid="'+data.msgid+'" class="'+leftRight+'" ><img src="'+data.head_img+'" class="user-face" onerror="noFind(this)" />'+content+'</li>');              
        $(".message-box .message ul").append(box);
        this.scrollbarBottom()
    },
    //解析消息体
    loadContent: function(action,ct){      
        action /=1;
        console.log(action)
        switch(action){
			//文字
			case 0:
			  ct = this.replaceFace(ct)
			  return `<div class="infos">${ct}</div>`;
			 //图片
            case 1 :    
			  return `<div class="infos picture"><img src="${ct}" onerror="noFind(this)" /><div class="remark">双击图片放大</div></div>`;
			  
			//视频
            case 2 :
              return `<div class="infos video"><video src="${ct}" controls="controls" preload="auto" controlsList="nofullscreen nodownload noremote footbar"  /></div>`;
            //商品
			case 3:
				var goods = JSON.parse(ct);
				return  `<div class="infos infos-goods">
					<div class="goods" data-gid="${goods.goods_id}" data-sku="${goods.sku_id}">
						<img src="${goods.thumb}" class="goods-img" onerror="noFind(this)" />
						<div class="goods-info">
							<h6>${goods.name}</h6>
							<div class="info">${goods.sku}</div>
							<div class="price">￥${goods.price}</div>
							<div class="remark">商品</div>
						</div>
					</div>
				</div>`;  
			//订单            
            case 4 :     
			 var order = JSON.parse(ct);			
             var html = `<div class="infos infos-order">      
                    <div class="order" data-sn="${order.order_sn}">                      
                    <div class="icon">
                       <i class="glyphicon glyphicon-file"></i>${order.order_sn} [${order.status}]                    
                    </div>
                    <table class="order-goods table">`;
                    
                        order.goods.forEach(function(good){
                            html+=`
                             <tr>
                                <td class="thumb"><img src="${good.goods_thumb}" /></td>
                                <td>
                                    <div class="title">${good.goods_name}</div>
                                    <div class="sku">${good.sku_name}</div>                                                           
                                </td>
                                <td class="num">X ${good.num} </td>
                                <td class="price">￥${good.goods_money}</td>
                            </tr>`; 
                        })         
                                         
                    html+=`</table>
                    <div class="info">
                        <div class="text-right">应付： <font color="red">￥${order.payable_money}元</font></div>                                             
                        <div class="address">
                           ${order.info.receiver_name} ${order.info.receiver_mobile}
                           ${order.info.province} ${order.info.city} ${order.info.district} ${order.info.receiver_address}
                        </div>
                        <div class="remark">${order.info.remark}</div>                        
                    </div>
                    <div class="remark mt10">订单</div>
                </div>`; 
            return html;
           default:  
                return `<div class="infos">${ct}</div>`;
        }
        
    },    
    //替换文字中的表情与换行
    replaceFace : function(content){        
        content = content.replace(/\r\n/g,"<br>")  
        content = content.replace(/\n/g,"<br>"); 
        content = ShopsFace.replaceFace(content);        
        return content;
    },
    //连接成功初始化
    init :function(){
         var that = this;
         that.getAjaxUserMessage() ;
         if(that.store.greeting  && that.store.is_robot == 1){
         
			var box = $('<li msgid="" class="left" time="" ><img src="'+ that.store.store_logo +'" class="user-face" onerror="noFind(this)" /><div class="infos">'+ that.store.greeting +'</div></li>');              
			$(".message-box .message ul").append(box);		
         } 
         if(that.store.is_robot == 1 && $(".addinfo").size() < 1){
             that.getAjaxReply(1); //常见问题 
         }          
    
        $(".message-txtarea-form").submit(function(){            
            var input = $.trim($(".message-txtarea-input").val())
            if(!input){
                return false;
            }            
            $(".message-txtarea-input").val("").blur();       
            $("#bottom_btns").hide();
            $("#face_list").hide();
            $(".message-txtarea-submit").hide();
            $(".message-txtarea-btns").show();                        
            that.sendMsg(input); 
            return false;
        })           
        const el = document.documentElement || document.body
        const originHeight = el.clientHeight;
        $(window).resize(function(){            
              const resizeHeight = el.clientHeight
              if (resizeHeight < originHeight) {
                //alert('键盘弹起')
              } else {
                //alert('键盘收起') 
                $(".message-txtarea-input").blur();
              }
        })    

        $(".message-txtarea-input").blur(function(){
            setTimeout(function(){
                that.reSize();
            },100)            
        });
       $(document).on("click", ".message-box .message ul li.loadmore",function(){   
            that.getAjaxUserMessage()            
        })   
        
       $(".message-txtarea-input").keyup(function(){           
           
            var val = $(this).val();
            if(val){
                $(".message-txtarea-submit").show();
                $(".message-txtarea-btns").hide();
            }else{
                $(".message-txtarea-submit").hide();
                $(".message-txtarea-btns").show();
            }
        })   
        $(".message-txtarea-submit").click(function(){            
            $(".message-txtarea-form").submit();
        });
 
        $(document).on("click",".message-box .message ul li .picture  img",function(){
            var src = $(this).attr("src")            
            that.showViewImage(src);
        })
        $(document).on("click","#showImageView",function(){            
            $("#showImageView").hide();
        })       
		$(document).on("change","#picture input",function(){		
			var fp = $(this);
			var file = fp[0].files[0];
			var url = URL.createObjectURL(file);  
			var head_img = $(".message-box .message").data('avatar')			
			
			content = '<div class="infos picture"><img src="'+url+'" /><div class="loading"></div></div>';
			var box = $('<li msgid="" class="right" time="" ><img src="'+head_img+'" class="user-face" onerror="noFind(this)" />'+content+'</li>');              
			$(".message-box .message ul").append(box);			
			
			//layer.msg("上线中")
			$("#bottom_btns").hide();
            $("#face_list").hide();
            that.reSize();  
			_uploadfile(file,'images',"image/png,image/jpg",function(result){
				console.log('ok',result)
				that.sendMsg(result.path,1,'',function(data){					
					box.find("li").attr('msgid',data.msgid);
					box.find("li").attr('time',data.create_time);
					box.find(".loading").addClass("remark").removeClass('loading').html("点击图片放大");			
				});				
			},function(){
				box.find(".loading").addClass("loading-error").removeClass('loading').html("上传失败");		
			},null,null);
            setTimeout(function(){
                  that.scrollbarBottom()   
            },500)            
			$(this).val('')
		})
		$(document).on("change","#video input",function(){		
			
			var fp = $(this);
			var file = fp[0].files[0];
			var url = URL.createObjectURL(file);  
			var head_img = $(".message-box .message").data('avatar')			
			
			content = '<div class="infos video"><video src="'+url+'" controls="controls" preload="auto" controlsList="nofullscreen nodownload noremote footbar" /><div class="loading"></div></div>';
			var box = $('<li msgid="" class="right" time=""><img src="'+head_img+'" class="user-face" onerror="noFind(this)" />'+content+'</li>');              
			$(".message-box .message ul").append(box);	
            
            $("#bottom_btns").hide();
            $("#face_list").hide();
            that.reSize(); 
			var video = box.find('video').get(0);
			video.play()		
			//layer.msg("上线中")
			box.find('video').on("canplaythrough",function(e){		 
				console.log(this.duration)
				var time = this.duration;			
				_uploadfile(file,'file',"video/mp4",function(result){
					console.log('ok',result)
					that.sendMsg(result.path,2,'',function(data){					
						box.find("li").attr('msgid',data.msgid);
						box.find("li").attr('time',data.create_time);
						box.find(".loading").remove();					
					});				
				},function(){
					box.find(".loading").addClass("loading-error").removeClass('loading').html("上传失败");			
								
				},time,null);
			})	
			setTimeout(function(){
                 that.scrollbarBottom()   
            },500) 
			$(this).val('')
		})   
        $(document).on("click",".addinfo .goods",function(){	
			var goods_id = $(this).data("gid");
            var sku_id = $(this).data("sku");
            var content = JSON.stringify({
                goods_id : goods_id,
                sku_id   : sku_id
            });
            $(".addinfo").remove();
            that.sendMsg(content,3);			
    
			setTimeout(function(){
                 that.scrollbarBottom()   
            },500) 	
		})  
        $(document).on("click",".addinfo .close",function(){				
            $(".addinfo").remove();
            return false;           	
		})  
         $(document).on("click",".addinfo .order",function(){	
			var order_sn = $(this).data("sn");   
            var content = JSON.stringify({  
                order_sn : order_sn,        
            });
            $(".addinfo").remove();
            that.sendMsg(content,4);			
    
			setTimeout(function(){
                 that.scrollbarBottom()   
            },500) 	
		})  
        
         setTimeout(function(){
              $(".addinfo").remove();
         },2500) 
       
        $(".message-txtarea .face-btn").click(function(){          
             $("#face_list").toggle();
             $("#bottom_btns").hide();
             that.reSize();
             return false;
        })
         $(".message-txtarea .message-txtarea-btns").click(function(){          
             $("#bottom_btns").toggle();
             $("#face_list").hide();
             that.reSize();
             return false;
        })
        
        $(document).click(function(e) {
            var modal = $('.message-titles')
            if(!modal.is(e.target) && modal.has(e.target).length === 0){ 	
                $("#bottom_btns").hide();
                $("#face_list").hide();
                that.reSize();
            }
        })
        
         $(document).on("click",".answer a",function(){				
            var content  = $(this).parents("dd").find("content").text();
            var box = $('<li msgid="" class="left" time="" ><img src="'+ that.store.store_logo +'" class="user-face" onerror="noFind(this)" /><div class="infos">'+ content +'</div></li>');              
			$(".message-box .message ul").append(box);	         	
		})  
    },  
    //发消息
    sendMsg :function(msg,type,session_title , callback ){    
        if(!this.clientHeader){    
           //layer.open({content: '你已下线',skin: 'msg',time:2});
           that.error("你已下线")      
           return false;
        }
        //私信没有注册
        if(! this.clientConnHeader){          
            window.location.reload();
            return false;
        }      
        var that = this;	
        var type = type ? type : 0 ;    
         msg = msg.replace(/<\/?.+?>/g, "");
        // msg = msg.replace(/ /g, "");
        console.log(msg)
        if(!msg){
            return true;
        }
        var obj = {				   
            type:type,
            content: msg,  
			session_title : session_title ? session_title : ""
        };
        $.post("/index.php/customer/chat/check_client_user?token="+ that.jstoken, obj ,function(result){
            if(result.code == 1){   
				if( $.type(callback)  == "function"){
                    callback(result.data);
                } else{
					that.rightAdd(result.data,"right")
				}
                that.socket.emit("sendmsg",{uid:result.data.service_user_id,msg:result.data})
            }
            //离线消息处理
            else if(result.code == 2){
               if( $.type(callback)  == "function"){
                    callback(result.data);
               } else{
					that.rightAdd(result.data,"right")
			   }  
               that.error(result.msg);   
               if(that.store.is_robot == 1){ 
                    that.getAjaxReply(2,obj.type,obj.content,obj.session_title); //离线1    
               } 
            }else{
               that.error(result.msg);   
            }
        })
    },
    scrollbarBottom : function(){
        var top =  $(".message-box .message ul").height();
        $(".message-box .message").scrollTop(top)
    },
    //提示错误
    error : function(msg){
        
         var box3 = $('<li class="times">'+msg+'</li>');
         $(".message-box .message ul").append(box3);
         this.scrollbarBottom()        
    },
   
    //获取与指定会员的聊天记录
    getAjaxUserMessage : function(){ 
        var that = this;
        var msgid = $(".message-box .message ul li[msgid]:eq(0)").attr("msgid")
        $(".message-box .message ul li.loadmore").remove();
        var top1 =  $(".message-box .message ul").height(); 
        $.post("/index.php/customer/chat/get_user_messages?token="+ that.jstoken,{msgid:msgid},function(result){
           if(result.code == 1){   		   
			 
               $.each( result.data,function(i,e){   
                    var leftRight = e.form_type == 2 ?  "left" : "right";
                    var content = that.loadContent(e.type,e.content) ;                
                    var box2 = $('<li msgid="'+ e.msgid +'" class="'+leftRight+'" time="'+e.create_time+'"><img src="'+e.head_img+'" class="user-face" onerror="noFind(this)"/>'+ content +'</li>');                       
                    $(".message-box .message ul").prepend(box2);  
               })    
               var top2 =  $(".message-box .message ul").height();              
               $(".message-box .message").scrollTop(top2 - top1)
           }    
           if(result.data.length >0){              
               var box3 = $('<li class="loadmore">查看更多消息</li>');    
               $(".message-box .message ul").prepend(box3);               
           }           
       });
    },
    //自动回复以及离线消息处理
    //type=1 为问题列表
    //type=2 为离线消息，提交服务器保存
    getAjaxReply : function(type,msg_type,content,session_title){
        var that = this;
         var query = {
             type:type,
             msg_type : msg_type || 0,
             content : content || "",
             session_title : session_title || "",
         };
         
        $.post("/index.php/customer/chat/get_replay?token="+ that.jstoken, query,function(result){
           if(result.code == 1 && result.data.length > 0){   	
               var box = $('<li msgid="" class="left" time=""><img src="'+that.store.store_logo+'" class="user-face" onerror="noFind(this)"/><dl class="answer infos"><dt>您是否遇到以下问题</dt></dl></li>')
               $.each( result.data,function(i,e){  
                    var box2 = $('<dd><a href="javascript:;">'+ e.problem +'</a><content style="display:none">'+ e.answer +'</content></dd>');                       
                    box.find("dl").append(box2)
               })                       
               $(".message-box .message ul").append(box);                
           }              
           setTimeout(function(){
              that.scrollbarBottom()   
           },50)            
       });        
    },
 
   
    //显示图片预览
    showViewImage : function(src){  
        $("#showImageView .imgView img").attr("src",src)        
        $("#showImageView").show(); 

    },
   //显示会员预览
    showViewUser : function(uid){
        
        
        
    },
    //页面变化时，重新调整窗口高度
    reSize : function(){
        var height = $(window).height();
        var bottom = $(".message-input").height();     
        $(".message").height(height - bottom );
       this.scrollbarBottom()   
    }

}